<template>
  <div class="pan-scene-management">
    <!-- 场景统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <div class="stats-container">
        <StatisticCard
          label="总场景"
          :value="statistics.total.toString()"
          icon="el-icon-document"
          type="primary"
        />
        <StatisticCard
          label="内置"
          :value="statistics.builtin.toString()"
          icon="el-icon-star-on"
          type="warning"
        />
        <StatisticCard
          label="自定义"
          :value="statistics.custom.toString()"
          icon="el-icon-edit"
          type="info"
        />
        <StatisticCard
          label="启用"
          :value="statistics.enabled.toString()"
          icon="el-icon-check"
          type="success"
        />
        <StatisticCard
          label="禁用"
          :value="statistics.disabled.toString()"
          icon="el-icon-close"
          type="danger"
        />
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 场景列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <div v-loading="loading" class="table-wrapper">
        <DynamicTable
          :data="sceneList"
          :columns="tableColumns"
          :loading="loading"
          :pagination="pagination"
          border
          row-key="id"
          @size-change="handleSizeChange"
          @current-page-change="handlePageChange"
        >
          <template #table-top>
            <div class="list-header">
              <div>
                <el-button type="primary" @click="handleAdd">
                  新增场景
                </el-button>
                <el-button type="primary" @click="handleExport">
                  导出场景
                </el-button>
              </div>
              <div class="header-right">
                <span class="sort-label">排序:</span>
                <el-select
                  v-model="filterForm.sort_by"
                  size="small"
                  style="width: 140px; margin-right: 10px"
                  @change="handleSearch"
                >
                  <el-option label="按场景名称" value="scene_name" />
                  <el-option label="按创建时间" value="created_time" />
                  <el-option label="按使用次数" value="usage_count" />
                  <el-option label="按启用状态" value="is_enabled" />
                </el-select>
                <el-select
                  v-model="filterForm.sort_order"
                  size="small"
                  style="width: 80px"
                  @change="handleSearch"
                >
                  <el-option label="升序" value="asc" />
                  <el-option label="降序" value="desc" />
                </el-select>
              </div>
            </div>
          </template>
          <template #scene_type="{ row }">
            <el-tag :type="row.is_builtin ? 'warning' : 'info'" size="small">
              {{ row.is_builtin ? "内置" : "自定义" }}
            </el-tag>
          </template>

          <template #is_enabled="{ row }">
            <el-switch
              :model-value="row.is_enabled"
              :disabled="loading"
              @change="(val: boolean) => handleToggleEnabled(row, val)"
            />
          </template>

          <template #priority_level="{ row }">
            <el-tag :type="getPriorityType(row.priority_level)" size="small">
              {{ getPriorityText(row.priority_level) }}
            </el-tag>
          </template>

          <template #action="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button size="small" type="warning" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              :disabled="row.is_builtin"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </DynamicTable>
      </div>
    </el-card>

    <!-- 场景详情弹窗 -->
    <DetailModal
      v-model="detailVisible"
      :scene-detail="sceneDetail"
      :loading="detailLoading"
    />

    <!-- 场景表单弹窗 -->
    <FormModal
      v-model="formVisible"
      :scene-detail="formSceneDetail"
      :is-edit="isEditMode"
      :department-options="props.departmentOptions"
      @save="handleFormSave"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import {
  getPanScenes,
  getPanSceneDetail,
  deletePanScene,
  togglePanScene,
  createPanScene,
  updatePanScene,
} from "../../servers";
import DetailModal from "./components/DetailModal.vue";
import FormModal from "./components/FormModal.vue";
import { ElMessageBox } from "element-plus";

// 定义props
const props = defineProps<{
  task?: string;
  departmentOptions?: Array<{ label: string; value: string }>;
}>();

// 页面状态
const loading = ref(false);
const detailVisible = ref(false);
const currentSceneId = ref<number | null>(null);
const sceneDetail = ref<any>(null);
const detailLoading = ref(false);

// 表单弹窗状态
const formVisible = ref(false);
const formSceneDetail = ref<any>(null);
const isEditMode = ref(false);

// 统计信息
const statistics = reactive({
  total: 0,
  builtin: 0,
  custom: 0,
  enabled: 0,
  disabled: 0,
});

// 场景列表数据
const sceneList = ref<
  Array<{
    id?: number;
    scene_id?: number;
    scene_code: string;
    scene_name: string;
    description: string;
    main_keywords: string[];
    aux_keywords: string[];
    is_builtin: boolean;
    is_custom: boolean;
    is_enabled: boolean;
    category: string;
    tags: string[];
    priority_level: "low" | "medium" | "high";
    created_by: string;
    updated_by: string;
    created_time: string;
    updated_time: string;
    usage_count: number;
    last_used_at: string;
    responsible_department: string;
    default_action: string;
    config: {
      auto_cleanup: boolean;
      retention_days: number;
    };
  }>
>([]);

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  scene_name: "",
  is_custom: "",
  is_enabled: "",
  created_by: "",
  sort_by: "usage_count",
  sort_order: "desc",
});

// 筛选表单配置
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "scene_name",
    name: "场景名称",
    type: "input",
    placeholder: "请输入场景名称",
    col: { span: 6 },
  },
  {
    key: "is_custom",
    name: "类型",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      { label: "内置", value: "false" },
      { label: "自定义", value: "true" },
    ],
    col: { span: 6 },
  },
  {
    key: "is_enabled",
    name: "状态",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      { label: "启用", value: "true" },
      { label: "禁用", value: "false" },
    ],
    col: { span: 6 },
  },
  {
    key: "created_by",
    name: "创建者",
    type: "select",
    placeholder: "全部",
    params: { clearable: true },
    options: [
      { label: "全部", value: "" },
      { label: "system", value: "system" },
      { label: "admin", value: "admin" },
    ],
    col: { span: 6 },
  },
]);

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "场景名称",
    prop: "scene_name",
    minWidth: 180,
    fixed: "left",
  },
  {
    label: "类型",
    prop: "is_builtin",
    minWidth: 100,
    align: "center",
    slot: "scene_type",
  },
  {
    label: "状态",
    prop: "is_enabled",
    minWidth: 100,
    align: "center",
    slot: "is_enabled",
  },
  {
    label: "使用次数",
    prop: "usage_count",
    minWidth: 100,
    align: "center",
  },
  {
    label: "优先级",
    prop: "priority_level",
    minWidth: 100,
    align: "center",
    slot: "priority_level",
  },
  {
    label: "操作",
    width: 200,
    fixed: "right",
    slot: "action",
  },
];

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 获取场景列表
const fetchSceneList = async (values?: any) => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      sort_by: filterForm.sort_by,
      sort_order: filterForm.sort_order,
      ...values,
    };

    // 处理筛选参数
    if (filterForm.scene_name) {
      params.scene_name = filterForm.scene_name;
    }
    if (filterForm.is_custom !== "") {
      params.is_custom = filterForm.is_custom === "true";
    }
    if (filterForm.is_enabled !== "") {
      params.is_enabled = filterForm.is_enabled === "true";
    }
    if (filterForm.created_by) {
      params.created_by = filterForm.created_by;
    }

    const result = await getPanScenes(params);

    sceneList.value = result.data.scenes;

    // 更新分页信息
    if (result.data.pagination) {
      pagination.total = result.data.pagination.total || 0;
      pagination.currentPage = result.data.pagination.page || 1;
      pagination.pageSize = result.data.pagination.per_page || 20;
    }

    // 计算统计数据
    calculateStatistics();
  } catch (error: any) {
    ElMessage.error(error?.message || "获取场景列表失败");
  } finally {
    loading.value = false;
  }
};

// 计算统计数据
const calculateStatistics = () => {
  statistics.total = sceneList.value.length;
  statistics.builtin = sceneList.value.filter((s) => s.is_builtin).length;
  statistics.custom = sceneList.value.filter((s) => s.is_custom).length;
  statistics.enabled = sceneList.value.filter((s) => s.is_enabled).length;
  statistics.disabled = sceneList.value.filter((s) => !s.is_enabled).length;
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  filterForm.scene_name = "";
  filterForm.is_custom = "";
  filterForm.is_enabled = "";
  filterForm.created_by = "";
  filterForm.sort_by = "usage_count";
  filterForm.sort_order = "desc";
  pagination.currentPage = 1;
  fetchSceneList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchSceneList(values);
};

// 分页操作（DynamicTable 事件）
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchSceneList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchSceneList();
};

// 获取优先级类型
const getPriorityType = (
  level: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    high: "danger",
    medium: "warning",
    low: "success",
  };
  return typeMap[level] || "info";
};

// 获取优先级文本
const getPriorityText = (level: string): string => {
  const textMap: Record<string, string> = {
    high: "高",
    medium: "中",
    low: "低",
  };
  return textMap[level] || level;
};

// 查看详情
const handleViewDetail = async (row: any) => {
  const sceneId = row.id || row.scene_id;
  if (!sceneId) {
    ElMessage.warning("场景ID不存在");
    return;
  }

  currentSceneId.value = sceneId;
  detailVisible.value = true;
  await fetchSceneDetail(sceneId);
};

// 获取场景详情
const fetchSceneDetail = async (sceneId: number) => {
  detailLoading.value = true;
  try {
    const result = await getPanSceneDetail(sceneId);
    sceneDetail.value = result.data;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取场景详情失败");
    sceneDetail.value = null;
  } finally {
    detailLoading.value = false;
  }
};

// 切换启用状态
const handleToggleEnabled = async (row: any, enabled: boolean) => {
  try {
    // 二次确认
    const action = enabled ? "启用" : "禁用";
    await ElMessageBox.confirm(
      `确定要${action}场景【${row.scene_name}】吗？`,
      `${action}确认`,
      {
        confirmButtonText: `确定${action}`,
        cancelButtonText: "取消",
        type: enabled ? "success" : "warning",
      }
    );

    loading.value = true;
    const result = await togglePanScene(row.id || row.scene_id, {
      is_enabled: enabled,
    });
    ElMessage.success(`场景已${action}`);

    // 如果有受影响的任务，显示警告信息
    if (result.data.affected_tasks && result.data.affected_tasks.count > 0) {
      ElMessage.warning(
        result.data.warning ||
          `该场景有${result.data.affected_tasks.count}个已启用的定时任务，${action}场景后这些任务执行时可能受到影响`
      );
    }

    // 更新列表数据
    // const index = sceneList.value.findIndex(
    //   (s) => (s.id || s.scene_id) === (row.id || row.scene_id)
    // );
    // if (index !== -1) {
    //   sceneList.value[index].is_enabled = enabled;
    //   sceneList.value[index].updated_time = result.data.updated_time;
    // }

    // // 如果当前详情是此场景，更新详情数据
    // if (
    //   sceneDetail.value &&
    //   (sceneDetail.value.id || sceneDetail.value.scene_id) ===
    //     (row.id || row.scene_id)
    // ) {
    //   sceneDetail.value.is_enabled = enabled;
    //   sceneDetail.value.updated_time = result.data.updated_time;
    // }

    // 重新计算统计
    calculateStatistics();
    fetchSceneList();
  } catch (error: any) {
    // 用户取消或操作失败，恢复开关状态
    row.is_enabled = !enabled;
    if (error !== "cancel") {
      ElMessage.error(error?.message || "操作失败");
    }
  } finally {
    loading.value = false;
  }
};

// 删除场景
const handleDelete = async (row: any) => {
  const sceneId = row.id || row.scene_id;
  if (!sceneId) {
    ElMessage.warning("场景ID不存在");
    return;
  }

  // 检查是否为内置场景
  if (row.is_builtin || !row.is_custom) {
    ElMessage.warning("内置场景不允许删除");
    return;
  }

  // 二次确认
  await ElMessageBox.confirm(
    `确定要删除场景【${row.scene_name}】吗？此操作不可恢复！`,
    "删除确认",
    {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消",
      type: "warning",
    }
  );

  try {
    await deletePanScene(sceneId, false);

    ElMessage.success("场景已删除");
    fetchSceneList();
    return;
  } catch (error: any) {
    ElMessage.error(error?.message || "操作失败");
  }
};

// 监听弹窗关闭，清空数据
watch(detailVisible, (newVal) => {
  if (!newVal) {
    currentSceneId.value = null;
    sceneDetail.value = null;
  }
});

// 新增场景
const handleAdd = () => {
  isEditMode.value = false;
  formSceneDetail.value = null;
  formVisible.value = true;
};

// 编辑场景
const handleEdit = async (row: any) => {
  const sceneId = row.id || row.scene_id;
  if (!sceneId) {
    ElMessage.warning("场景ID不存在");
    return;
  }

  isEditMode.value = true;
  formVisible.value = true;

  // 获取场景详情用于编辑
  try {
    const result = await getPanSceneDetail(sceneId);

    formSceneDetail.value = result.data;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取场景详情失败");
    formVisible.value = false;
  }
};

// 保存表单（新增或编辑）
const handleFormSave = async (data: any) => {
  try {
    loading.value = true;

    if (isEditMode.value && formSceneDetail.value) {
      // 编辑模式
      const sceneId =
        formSceneDetail.value.id || formSceneDetail.value.scene_id;
      await updatePanScene(sceneId, data);

      ElMessage.success("场景更新成功");
      formVisible.value = false;
      // 刷新列表
      fetchSceneList();
    } else {
      // 新增模式
      await createPanScene(data);

      ElMessage.success("场景创建成功");
      formVisible.value = false;
      // 刷新列表
      fetchSceneList();
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "操作失败");
  } finally {
    loading.value = false;
  }
};

// 导出场景
const handleExport = async () => {
  try {
    // 确认导出
    await ElMessageBox.confirm(
      "确定要导出场景配置吗？将导出当前筛选条件下的所有场景数据。",
      "确认导出",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
      }
    );

    loading.value = true;
    ElMessage.info("正在获取场景数据，请稍候...");

    // 获取所有场景数据（使用较大的 per_page 获取全部数据）
    const allScenes: any[] = [];
    let currentPage = 1;
    const perPage = 100; // 每页获取100条
    let hasMore = true;

    // 构建查询参数（使用当前筛选条件）
    const baseParams: any = {
      sort_by: filterForm.sort_by,
      sort_order: filterForm.sort_order,
    };

    if (filterForm.scene_name) {
      baseParams.scene_name = filterForm.scene_name;
    }
    if (filterForm.is_custom !== "") {
      baseParams.is_custom = filterForm.is_custom === "true";
    }
    if (filterForm.is_enabled !== "") {
      baseParams.is_enabled = filterForm.is_enabled === "true";
    }
    if (filterForm.created_by) {
      baseParams.created_by = filterForm.created_by;
    }

    // 分页获取所有数据
    while (hasMore) {
      const params = {
        ...baseParams,
        page: currentPage,
        per_page: perPage,
      };

      const result = await getPanScenes(params);
      const scenes = result.data?.scenes || [];
      allScenes.push(...scenes);

      // 判断是否还有更多数据
      const total = result.data?.pagination?.total || 0;
      if (allScenes.length >= total || scenes.length < perPage) {
        hasMore = false;
      } else {
        currentPage++;
      }
    }

    if (allScenes.length === 0) {
      ElMessage.warning("没有可导出的数据");
      return;
    }

    // 构建 CSV 数据
    const headers = [
      "场景ID",
      "场景代码",
      "场景名称",
      "描述",
      "类型",
      "状态",
      "主关键词",
      "辅助关键词",
      "分类",
      "标签",
      "优先级",
      "使用次数",
      "创建者",
      "更新者",
      "创建时间",
      "更新时间",
      "最后使用时间",
      "责任部门",
      "默认动作",
    ];

    // 转换数据行
    const rows = allScenes.map((scene) => {
      const escapeCSV = (value: any): string => {
        if (value === null || value === undefined) return "";
        const str = String(value);
        // 如果包含逗号、引号或换行符，需要用引号包裹并转义引号
        if (str.includes(",") || str.includes('"') || str.includes("\n")) {
          return `"${str.replace(/"/g, '""')}"`;
        }
        return str;
      };

      return [
        scene.id || scene.scene_id || "",
        scene.scene_code || "",
        scene.scene_name || "",
        scene.description || "",
        scene.is_builtin ? "内置" : "自定义",
        scene.is_enabled ? "启用" : "禁用",
        Array.isArray(scene.main_keywords)
          ? scene.main_keywords.join("; ")
          : "",
        Array.isArray(scene.aux_keywords) ? scene.aux_keywords.join("; ") : "",
        scene.category || "",
        Array.isArray(scene.tags) ? scene.tags.join("; ") : "",
        scene.priority_level === "low"
          ? "低"
          : scene.priority_level === "high"
          ? "高"
          : "中",
        scene.usage_count || 0,
        scene.created_by || "",
        scene.updated_by || "",
        scene.created_time || "",
        scene.updated_time || "",
        scene.last_used_at || "",
        scene.responsible_department || "",
        scene.default_action || "",
      ].map(escapeCSV);
    });

    // 构建 CSV 内容（添加 BOM 以支持 Excel 正确显示中文）
    const csvContent =
      "\uFEFF" +
      headers.join(",") +
      "\n" +
      rows.map((row) => row.join(",")).join("\n");

    // 创建下载链接
    const blob = new Blob([csvContent], {
      type: "text/csv;charset=utf-8;",
    });
    const link = document.createElement("a");
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    const date = new Date().toISOString().slice(0, 10).replace(/-/g, "");
    link.setAttribute("download", `场景配置列表_${date}.csv`);
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    ElMessage.success(`成功导出 ${allScenes.length} 条场景数据`);
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("导出失败:", error);
      ElMessage.error("导出失败：" + (error?.message || "未知错误"));
    }
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  fetchSceneList();
});
</script>

<style scoped lang="scss">
.pan-scene-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .stats-card,
  .filter-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-content {
    padding: 5px 0;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .list-title {
      font-size: 16px;
      font-weight: 500;
      margin: 0;
      color: #303133;
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 10px;

      .sort-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .table-wrapper {
    min-height: 200px;
  }
}
</style>
